<?php


namespace App\Http\Services;

use App\Models\File;
use App\Models\Label;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FileService extends BaseService
{

    public function upload(Request $request)
    {
        $params = $request->all();
        //dd($request->hasFile('file'));
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            $file = $request->file('file');
            $allowed_extensions = ["png", "jpg", "gif", "jpeg", "zip", "rar", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "pdf", "csv"];
            $extension = $file->getClientOriginalExtension();
            if (!in_array($extension, $allowed_extensions) || 0) {
                throw new Exception('只能上传' . implode('、', $allowed_extensions) . '格式的文件.');
            } else {
                //原上传文件名称
                $client_name = $file->getClientOriginalName();
                //文件大小
                $file_size = $file->getSize();
                $month = monthConvert(date('m'));
                $destinationPath = 'uploads/'.date('Y') . '/' . $month . '/';
                $preFileName = md5(time() . rand(1000, 9999));
                $fileName = $preFileName . '.' . $extension;
                $result = Storage::disk('public')->putFileAs($destinationPath, $file, $fileName);
                $userId = $this->getCurrentUser()->id ?? 0;
                //保存到数据库
                $file = new File();
                $file->original_name = $fileName;
                $file->name = $client_name;
                $file->size = $file_size;
                $file->type = $request->input('type') ?? 'file';
                $file->ext = $extension;
                $file->path = $destinationPath . $fileName;
                $file->creator_id = $userId;
                $save_result = $file->save();
                if ($result && $save_result) {
                    $file->url = asset(Storage::url($file->path));
                    return $file;
                } else {
                    throw new Exception('文件上传失败');
                }
            }
        } else {
            throw new Exception('文件未上传或不合法');
        }
    }

    public function download($params)
    {
        $file = File::find($params['id']);
        if (!$file || !isset($file->path)) {
            throw new Exception('文件不存在');
        }
        return Storage::download($file->path);
    }

    public function delete($params)
    {
        $url = $params['filePath'];
        $path = strstr($url, 'uploads');
        if($path){
            $userId = $this->getCurrentUser()->id ?? 0;
            $result = File::where('path',$path)->where('creator_id',$userId)->delete();
            //删除文件
            Storage::disk('public')->delete($path);
        }

        return true;
    }



}
